package com.springboot.middleware.middleware_redisson.server.controller;

import com.google.common.base.Strings;
import com.springboot.middleware.middleware_redisson.api.enums.StatusCode;
import com.springboot.middleware.middleware_redisson.api.response.BaseResponse;
import com.springboot.middleware.middleware_redisson.server.dto.BookRobDto;
import com.springboot.middleware.middleware_redisson.server.service.BookRobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BookRobController {
    private static final Logger log = LoggerFactory.getLogger(BookRobController.class);
    private static final String prefix = "book/rob";

    @Autowired
    BookRobService bookRobService;

    /**
     * 用户抢购书籍
     * @param dto 请求
     * @return 状态码
     */
    @RequestMapping(value = prefix + "/request", method = RequestMethod.GET)
    public BaseResponse bookRobWithNoLock(BookRobDto dto) {
        //合法性检测
        if (Strings.isNullOrEmpty(dto.getBookNo()) || dto.getUserId() == null || dto.getUserId() <= 0) {
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            bookRobService.rob(dto);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }
}
